package thread.application;

import lombok.extern.log4j.Log4j2;

/**
 * @author ykh
 */
@Log4j2
public class TPTInterrupt {

    private Thread thread;

    public void start(){
        thread = new Thread(() -> {
            while(true) {
                Thread current = Thread.currentThread();
                //当发现当前线程被打断后结束当前线程
                if(current.isInterrupted()) {
                    log.debug("料理后事");
                    break;
                }
                try {
                    //阻塞状态的线程被打断会抛出异常,并将打断标记设为false
                    Thread.sleep(1000);
                    log.debug("将结果保存");
                } catch (InterruptedException e) {
                    current.interrupt();//将打断标记设为true
                }
                // 执行监控操作
            }
        },"监控线程");
        thread.start();
    }

    public void stop() {
        //interrupt调用后，线程被打断标记标志
        thread.interrupt();
    }

    public static void main(String[] args) throws InterruptedException {
        TPTInterrupt t = new TPTInterrupt();
        t.start();
        Thread.sleep(3500);
        log.debug("stop");
        t.stop();
    }
}
